dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.TitlePane");
dojo.require("dijit.Tree");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("opm.widgets.component.Group");
dojo.require("opm.widgets.component.ApplicationProperty");
dojo.require("opm.widgets.component.ClassDef");
dojo.require("opm.widgets.component.ClassInst");
dojo.require("opm.widgets.component.Storage");
dojo.require("opm.widgets.component.Search");
dojo.require("opm.widgets.component.Security");
var OPM = {
   callAjaxWidget : function(data, contentId, ajaxType){
      switch (ajaxType){
      case "callXhrGetJson":
         OPM.ajaxWidget(data, contentId).callXhrGetJson();
         break;
      }
   },
   ajaxWidget : function(data, contentId){
      var args = this._createArgsOfWidget(data, "ajaxWidget", contentId);
      var ajaxWidget = dijit.byId(args.id);
      if (!ajaxWidget){
         ajaxWidget = new opm.widgets.Ajax(args);
      }else {
         ajaxWidget.setAtts(args);
      }
      return ajaxWidget;
   },
   applicationPropertyWidget:function(data, contentId){
       var dataWidget = this._createArgsOfWidget(data, "applicationPropertyWidget", contentId);
       var applicationPropertyWidget = this._getWidget(dataWidget, function(args){
          return new opm.widgets.component.ApplicationProperty(args);
       });
       return applicationPropertyWidget;
   },
   classDefWidget:function(data, contentId){
       var dataWidget = this._createArgsOfWidget(data, "classDefWidget", contentId);
       var customWidget = this._getWidget(dataWidget, function(args){
          return new opm.widgets.component.ClassDef(args);
       });
       return customWidget;
   },
   classInstWidget:function(data, contentId){
       var dataWidget = this._createArgsOfWidget(data, "classInstWidget", contentId);
       var customWidget = this._getWidget(dataWidget, function(args){
          return new opm.widgets.component.ClassInst(args);
       });
       return customWidget;
   },
   storageWidget:function(data, contentId){
       var dataWidget = this._createArgsOfWidget(data, "storageWidget", contentId);
       var customWidget = this._getWidget(dataWidget, function(args){
          return new opm.widgets.component.Storage(args);
       });
       return customWidget;
   },
   searchWidget:function(data, contentId){
       var dataWidget = this._createArgsOfWidget(data, "searchWidget", contentId);
       var customWidget = this._getWidget(dataWidget, function(args){
          return new opm.widgets.component.Search(args);
       });
       return customWidget;
   },
   securityWidget:function(data, contentId){
      var dataWidget = this._createArgsOfWidget(data, "securityWidget", contentId);
      var customWidget = this._getWidget(dataWidget, function(args){
         return new opm.widgets.component.Security(args);
      });
      return customWidget;
  },
   groupWidget:function(data, contentId){
      var dataWidget = this._createArgsOfWidget(data, "groupWidget", contentId);
      var customWidget = this._getWidget(dataWidget, function(args){
         return new opm.widgets.component.Group(args);
      });
      return customWidget;
  },
   genericSearchWidget: function(data){
      var genericSearchWidget = this._getWidget(data, function(args){
         return new opm.widgets.GenericSearchForm(args);
      });
      return genericSearchWidget;
   },
   genericFormWidget: function(data){
      var genericFormWidget = this._getWidget(data, function(args){
         return new opm.widgets.GenericForm(args);
      });
      return genericFormWidget;
   },
   genericPageWidget: function(data){
      var genericPageWidget = this._getWidget(data,function(args){
         return new opm.widgets.GenericPage(args);
      });
      return genericPageWidget;
   },
   genericFormDialogWiget: function(formData, contentId){
      var data=this._createArgsOfWidget(formData, "genericFormDialogWiget", contentId);
      data.widgetId = "genericFormDialogWiget";
      var genericFormDialogWiget = this._getWidget(data,function(args){
         return new opm.widgets.GenericFormDialog(args);
      });
      return genericFormDialogWiget;
   },
   _getWidget:function (data,newInstanceFunction){
      var commonWidget = dijit.byId(data.widgetId);
      if (data.contentId == null){
         return commonWidget;
      }
      if (commonWidget == null && newInstanceFunction != null){
         var args=this._createArgsOfWidget({}, data.widgetId, data.contentId);
         commonWidget = newInstanceFunction(args);
      }
      for (var property in data){
         switch (property){
         case "dataform":
            commonWidget.setDataForm(data[property]);
            break;
         case "dataPage":
            commonWidget.setDataPage(data[property]);
            break;
         default:
            commonWidget[property] = data[property];
            break;
         }
      }
      return commonWidget;
   },
   _createArgsOfWidget: function(args, widgetId, contentId){
      var _args = (args==null)?{}:args;
      if (widgetId != null){
         _args.id = widgetId;
      }
      _args.widgetId= widgetId;
      _args.contentId = contentId;
      return _args;
   }
};

function setupLayout(){
   var layout = new dijit.layout.BorderContainer({style:"height: 100%; width: 100%"},"mainLayout");
   var header = new dijit.layout.ContentPane({region: "top"},"header");
   var left = new dijit.layout.ContentPane({region: "leading"},"left");
   var center = new dijit.layout.ContentPane({region: "center"},"center");
   var footer = new dijit.layout.ContentPane({region: "bottom"},"footer");
   layout.addChild(header);
   layout.addChild(left);
   layout.addChild(center);
   layout.addChild(footer);
   layout.startup();
}

function setupMainMenu(){
   dojo.query("#menuConfiguration2 a").onclick(function (){
      var value = dojo.query('input[type="hidden"]', this)[0].value;
      switch (value) {
      case 'group':
         OPM.groupWidget({},'center').show();
         break;
      case 'user':
         OPM.groupWidget({},'center').showUser();
         break;
      }
   });

   dojo.query("#hrefViewCreateStorage").onclick(function (){
      var showAddStorageFormURL = dojo.query('input[type="hidden"]', this)[0].value;
      OPM.storageWidget({defaultURL:showAddStorageFormURL},'center').showAddForm(showAddStorageFormURL);
   });

   systemDataStore = new dojo.data.ItemFileReadStore({
      data:dataClassDefinitionTree.dataTree
   });
   
   var treeModel = new dijit.tree.ForestStoreModel({
      store:systemDataStore,
      query:{type:"parentNode"},
      childrenAttrs:["children"]
   });
   classDefTree = new dijit.Tree({model: treeModel, showRoot:false}, 'classDefTree');
   _initSelectNode(classDefTree);
}

var selectedItem = null;
function _initSelectNode(classDefTree){
   dojo.connect(classDefTree, "onClick", function(item){
       selectedItem = item;
       var nodeType = item.nodeType;
       if (nodeType=='storage'){
          var storageWidgetObject = OPM.storageWidget({},'center');
          storageWidgetObject.showViewStorage(item.hrefView);
          retrieveItemsTree(item.href);
       }else if (nodeType=='properties'){
          OPM.applicationPropertyWidget({defaultURL:item.href},'center').displayApplicationProperties();
       }else if(nodeType=='document'){
          retrieveItemsTree(item.childrenURL);
          OPM.classDefWidget({defaultURL:item.href},'center').displayClassDefMenu();
       }
    });
}

function retrieveItemsTree(href){
    if ((!(selectedItem.hasClicked == "true")) && href != null){
        var args = {ajaxUrl: href, callback: addItemsStorageData};
        OPM.ajaxWidget(args, 'mainMenu').callXhrGetJson();
    }
}

function addItemsStorageData(data){
    var children = new Array();
    for (var index=0; index<data.length; index++){
       var itemMenu = data[index];
       children.push(itemMenu);
    }
    selectedItem.children = children;
    selectedItem.type = "parentNode";
    selectedItem.hasClicked = "true";
    callReloadTree();
}

var refreshCurrentNodeItemTree = function(){
    var href = selectedItem.childrenURL;
    if (href != null){
        var args = {ajaxUrl: href, callback: addItemsStorageData};
        OPM.ajaxWidget(args, 'mainMenu').callXhrGetJson();
    }
}

var addStorageNodeItem = function(storageId, displayName){
    var nodeItem = {id:storageId,nodeType:'storage',href:'auth/classDef/menu/'+storageId+'/firstItemsTree', hrefView:'${auth}/storage/'+storageId+'/view', name:displayName,type:'parentNode'};
    dataClassDefinitionTree.dataTree.items.push(nodeItem);
    callReloadTree();
}

var connectEvent = function (widgetId, component, eventName) {
    var componentObject = dijit.byId(widgetId);
    componentObject.callEvent(eventName);
}

function addChildItemToTree(item){
    var children = selectedItem.children;
    if (children == null){
        children = new Array(); 
    }
    children.push(itemMenu);
    selectedItem.children = children;
    callReloadTree();
}

function callReloadTree(){
   _reloadTree("classDefTree",dataClassDefinitionTree);
}

function _reloadTree(dijitId, dataStoreTree){
   var tree = dijit.byId(dijitId);
   tree.model.store.clearOnClose = true;
   tree.model.store.close();
   tree._itemNodesMap = {};
   tree.rootNode.state = "UNCHECKED";
   tree.model.root.children = null;
   tree.rootNode.destroyRecursive();
   tree.model.store.data = dataStoreTree.dataTree;
   tree.model.rootLabel = dataStoreTree.rootLabel;
   tree.model.constructor(tree.model);
   tree.postMixInProperties();
   tree._load();
}